package com.shadow.output.study.algorithm.sequence;

public class BruteForce implements Sequence {

    @Override
    public int indexOf(String text, String pattern) {
        if (null == text || null == pattern) {
            return -1;
        }
        char[] tchars = text.toCharArray(), pchars = pattern.toCharArray();
        if (tchars.length == 0 || pchars.length == 0 || tchars.length < pchars.length) {
            return -1;
        }

        // pi 指向模式串，ti 指向文本串，指向的两个位置字符进行比较
        int pi = 0, ti = 0;
        int iMax = tchars.length - pchars.length;
        // ti - pi：为一轮比较中，text文本串首个比较字符的下标。
        while (pi < pchars.length && ti - pi <= iMax) {
            if (pchars[pi] == tchars[ti]) {
                pi ++;
                ti ++;
            } else {
                // 从之前首个比较字符的下一个开始
                ti = ti - pi + 1;
                // pi 置 0
                pi = 0;
            }
        }

        return pi == pchars.length ? ti - pi : -1;
    }
}
